/**
 * 
 */
package pt.mleiria.network;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import pt.mleiria.network.utils.ServerConstants;

/**
 * @author NB13712
 * 
 */
public class ServerBot {
	
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			final ServerSocket botSocket = new ServerSocket(ServerConstants.PORT);
			
			boolean initServer = true;
			System.out.println("Accepting conn from commandBot");
			
			final Socket connectionSocket = botSocket.accept();
			
			while (initServer) {
				//Receive commands from command bot
				final BufferedReader inFromCommandBot = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
				//Send results to command bot
				final DataOutputStream outToCommandBot = new DataOutputStream(connectionSocket.getOutputStream());
				
				final int cmdId = inFromCommandBot.read();
				System.out.println("Received cmdId: " + cmdId);
				final Command cmd = Command.parse(cmdId);
				System.out.println("Received id:" + cmdId + ";name: " + cmd);
				if(cmd.equals(Command.STOP)){
					System.out.println(cmd + " Command. Closing connection...");
					outToCommandBot.writeBytes(cmd.name());
					connectionSocket.close();
					botSocket.close();
					initServer = false;
				}else{
					System.out.println("Command Name: " + cmd + " executed.");
					outToCommandBot.writeBytes(cmd.name());
				}
				
				
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
